package com.turing.data.scripts.yhlc.filter

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.TypeReference
import com.turing.common.entity.TextVO
import com.turing.common.util.FileUtils
import com.turing.common.util.Log
import com.turing.common.util.StringUtils
import com.turing.data.engine.TextUtils
import com.turing.data.engine.utils.MatchedGroup
import com.turing.data.engine.utils.ScriptsUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import org.apache.commons.lang.SerializationUtils
import org.springframework.util.CollectionUtils

import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * @description: 银行理财 - 业务类别
 * @author: mazhishen
 */

class BussinessType_30250_46_filter {

    static List< TaskElementVO.DrawResultVO > doConvert(DependParamsVO dependParams){

        def REGEX_BACKUP_1 = "业务类型"
        def REGEX_BACKUP_2 = "业务类别"
//        def REGEX_BACKUP_1 = "确认份额"
//        def REGEX_BACKUP_2 = "本期申购份额"
//        def REGEX_BACKUP_3 = "总份额"
//        def REGEX_BACKUP_4 = "期末份额"

        List< TaskElementVO.DrawResultVO > trueValueSet = new ArrayList<>()
        List<TaskElementVO.DrawResultVO > resultVOs = ScriptsUtils.tryInitResult(dependParams)
        try {
            if (resultVOs!=null && resultVOs.size()>0) {
                for (int i = 0; i < resultVOs.size(); i++) {
                    def drawResultVO = resultVOs.get(i)
                    def childTaskSn = drawResultVO.childTaskSn
    //                    if(null == childTaskSn || childTaskSn == ""){
    //                        return resultVOs
    //                    }
                    def start = drawResultVO.start
                    def end = drawResultVO.end
                    def text = drawResultVO.text
                    text = text.replaceAll("\n","")
                    def textPathMap = dependParams.textPathMap
                    def rawPath = textPathMap.get(drawResultVO.childTaskSn)

                    if(rawPath == null){
                        continue
                    }

                    def rawText = FileUtils.loadJson(rawPath)
                    def expandOffset = 0
                    //往前10个字符搜索
                    while( expandOffset < 20 && start > expandOffset ){
                        def expandString = rawText.substring(start-expandOffset,start)
                        if( expandString =~ REGEX_BACKUP_1
                            || expandString =~ REGEX_BACKUP_2
    //                        || expandString =~ REGEX_BACKUP_3
    //                        || expandString =~ REGEX_BACKUP_4
                        )
                        {
                            trueValueSet.add(drawResultVO)
                            return trueValueSet
                        }
                        expandOffset ++
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace()
        }

        try{
            println("BussinessType_trueValueSet1="+trueValueSet)
            if(trueValueSet.size()==0){

                String REGEX = /申购确认/
                String REGEX_1 = /认购确认/
                String REGEX_2 = /申购申请/
                String REGEX_3 = /赎回确认/
                String REGEX_4 = /赎回到账/
                String REGEX_5 = /申购/
                String REGEX_6 = /赎回/
                String REGEX_7 = /赎回确认/
                def REGEXES = [REGEX,REGEX_1,REGEX_2,REGEX_3,REGEX_4,REGEX_5,REGEX_6,REGEX_7]
                for(REGEX0 in REGEXES){
                    dependParams.JSONTextMap.forEach(
                            { childTaskSn, jsonText ->
                                doRuleExtractLimit100(REGEX0,childTaskSn, dependParams, jsonText, trueValueSet)
                            }
                    )
                    println("BussinessType_trueValueSet2="+trueValueSet)
                    if(!CollectionUtils.isEmpty(trueValueSet)){
                        def text0 = trueValueSet[0].text
                        if(text0.equals("认购确认")){
                            trueValueSet[0].businessValue = "申购确认"
                            trueValueSet[0].type = 1
                        }
                        return trueValueSet
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace()
        }

        //如果过滤后没有值，那么就默认返回模型给的第一个值
        if(trueValueSet.size() == 0 && resultVOs.size() > 0 && !StringUtils.isEmpty(resultVOs[0].text)){
            trueValueSet.add(resultVOs[0])
            return  trueValueSet
        }

        TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
        defaultDrawResultVO.text = ""
        trueValueSet.add(defaultDrawResultVO)
        return  trueValueSet

    }

     static void doRuleExtractLimit100(String regex,String childTaskSn, DependParamsVO dependParams, String jsonText, List<TaskElementVO.DrawResultVO> trueValueSet) {
        if (CollectionUtils.isEmpty(trueValueSet)) {
            TaskElementVO.DrawResultVO initDrawResultVO = new TaskElementVO.DrawResultVO();
            initDrawResultVO.setChildTaskSn(childTaskSn);

            StringBuilder cleanText = new StringBuilder();
            List<TextVO> textVOS = JSON.parseObject(jsonText, new TypeReference<ArrayList<TextVO>>() {});
            for (TextVO textVO : textVOS) {
                List<TextVO.Line> lines = textVO.getParagraphs().get(0).getLines();
                for (TextVO.Line line : lines) {
                    if(line.getObjType().equals("textLine")){
                        cleanText.append(line.getObjContent());
                    }else{
                        String objContent = line.getObjContent();
                        JSONArray rows = JSONArray.parseArray(objContent);
                        for (Object row : rows) {
                            JSONObject rowObj = JSONObject.parseObject(JSON.toJSONString(row));
                            String rowContent = rowObj.getString("objContent");
                            cleanText.append(rowContent);
                        }
                    }
                }
            }
            def cleanTextLimit100 = cleanText.toString()
            if(cleanText.length()>100){
                cleanTextLimit100 = cleanTextLimit100.substring(0,100)
            }
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(cleanTextLimit100.toString());
            List<MatchedGroup> matchedGroupList = new ArrayList<>();
            MatchedGroup matchedGroup;
            while (matcher.find()) {
                Log.info( ">>>>>>>>>>>> matcher found..." + matcher.group() );
                matchedGroup = new MatchedGroup();
                matchedGroup.setSonOfStr(matcher.group());//子串内容
                matchedGroup.setIndexStart(matcher.start());//子串在全文中的开始位置
                matchedGroup.setIndexEnd(matcher.end());//子串在全文中的结束位置
                matchedGroupList.add(matchedGroup);
            }

            Log.info( ">>>>>>>>>> matched group is " + matchedGroupList );
            if (CollectionUtils.isEmpty(matchedGroupList)) {
                return;
            }

            matchedGroup = Collections.min(matchedGroupList);
            initDrawResultVO.setStart((int) matchedGroup.getIndexStart());
            initDrawResultVO.setEnd((int) matchedGroup.getIndexEnd());
            Log.info( ">>>>>>> init Draw Result VO " + initDrawResultVO.toString() );
            Log.info( ">>>>>>> initDraw start " + initDrawResultVO.getStart() + ", end " + initDrawResultVO.getEnd() );
            Log.info( ">>>>>>> Matched start " + matchedGroup.getIndexStart() + ", end " + matchedGroup.getIndexEnd() );
            TaskElementVO.DrawResultVO ObjectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(initDrawResultVO);
            ObjectNew = TextUtils.correctPosInfoByIndex(ObjectNew, initDrawResultVO.getStart(), initDrawResultVO.getEnd(), jsonText, matchedGroup.getSonOfStr());
            trueValueSet.add(ObjectNew);
        }
    }

}
